package zonghe.exer02;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int k = sc.nextInt();
        while (k > 0) {
            int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt();
            int t = sc.nextInt();
            int[][][] mat = new int[a][b][c];
            for (int i = 0; i < a; i++) {
                for (int j = 0; j < b; j++) {
                    for (int l = 0; l < c; l++) {
                        mat[i][j][l] = sc.nextInt();
                    }
                }
            }
            boolean[][][] flag = new boolean[a][b][c];
            int[][] nextPos = {{0, 0, 1}, {0, -1, 0}, {0, 0, -1}, {0, 1, 0}, {1, 0, 0}, {-1, 0, 0}};
            flag[0][0][0] = true;
            Queue<int[]> queue = new LinkedList<>();
            queue.offer(new int[] {0, 0, 0});
            int step = 0;
            boolean findFlag = false;
            while (!queue.isEmpty()) {
                int size = queue.size();
                while (size > 0) {
                    int[] top = queue.poll();
                    for (int i = 0; i < 6; i++) {
                        int aPos = top[0] + nextPos[i][0];
                        int bPos = top[1] + nextPos[i][1];
                        int cPos = top[2] + nextPos[i][2];
                        if (aPos == a - 1 && bPos == b - 1 && cPos == c - 1) {
                            System.out.println(step + 1);
                            findFlag = true;
                            break;
                        }
                        if (aPos >= 0 && aPos < a && bPos >= 0 && bPos < b && cPos >= 0 && cPos < c && !flag[aPos][bPos][cPos] && mat[aPos][bPos][cPos] == 0) {
                            flag[aPos][bPos][cPos] = true;
                            queue.offer(new int[] {aPos, bPos, cPos});
                        }
                    }
                    if (findFlag) {
                        break;
                    }
                    size--;
                }
                if (findFlag) {
                    break;
                }
                step++;
                if (step == t) {
                    break;
                }
            }
            if (!findFlag) {
                System.out.println(-1);
            }
            k--;
        }
    }
}